import auth from '@/plugins/auth'
import router, { constantRoutes, dynamicRoutes, allPagesRoutes } from '@/router'
import { getRouters } from '@/api/menu'
import Layout from '@/layout/index'
import ParentView from '@/components/ParentView'
import InnerLink from '@/layout/components/InnerLink'
import useUserStore from '@/store/modules/user'
import { cloneDeep } from 'lodash-es'

// 匹配views里面所有的.vue文件
const modules = import.meta.glob('./../../views/**/*.vue')

const usePermissionStore = defineStore(
  'permission',
  {
    state: () => ({
      routes: [],
      addRoutes: [],
      defaultRoutes: [],
      topbarRouters: [],
      sidebarRouters: []
    }),
    actions: {
      setRoutes(routes) {
        this.addRoutes = routes
        this.routes = constantRoutes.concat(routes)
      },
      setDefaultRoutes(routes) {
        this.defaultRoutes = constantRoutes.concat(routes)
      },
      setTopbarRoutes(routes) {
        this.topbarRouters = routes
      },
      setSidebarRouters(routes) {
        this.sidebarRouters = routes
      },
      generateRoutes(res) {
        return new Promise(resolve => {
          // 向后端请求路由数据
          // getRouters().then(res => {
            const userStore = useUserStore()
            // const buttons = getLeafButtonIds(res.allMenu.children)
            // userStore.setPermissions(buttons)
            const aa = getAllIds(res.data)
            const newAllPagesRoutes = setTreeHidden(allPagesRoutes, new Set(aa))
            const sdata = cloneDeep(newAllPagesRoutes)
            const defaultData = cloneDeep(newAllPagesRoutes)
            const sidebarRoutes = filterAsyncRouter(sdata)
            const rewriteRoutes = filterAsyncRouter(sdata, false, true)
            console.log('rewriteRoutes', rewriteRoutes)

            const defaultRoutes = filterAsyncRouter(defaultData)
            // const asyncRoutes = filterDynamicRoutes(dynamicRoutes)
            dynamicRoutes.forEach(route => { router.addRoute(route) })
            this.setRoutes(rewriteRoutes)
            this.setSidebarRouters(constantRoutes.concat(sidebarRoutes))
            this.setDefaultRoutes(sidebarRoutes)
            this.setTopbarRoutes(defaultRoutes)
            resolve(rewriteRoutes)

            // const sdata = JSON.parse(JSON.stringify(res.data))
            // const rdata = JSON.parse(JSON.stringify(res.data))
            // const defaultData = JSON.parse(JSON.stringify(res.data))
            // const sidebarRoutes = filterAsyncRouter(sdata)
            // const rewriteRoutes = filterAsyncRouter(rdata, false, true)
            // const defaultRoutes = filterAsyncRouter(defaultData)
            // const asyncRoutes = filterDynamicRoutes(dynamicRoutes)
            // asyncRoutes.forEach(route => { router.addRoute(route) })
            // this.setRoutes(rewriteRoutes)
            // this.setSidebarRouters(constantRoutes.concat(sidebarRoutes))
            // this.setDefaultRoutes(sidebarRoutes)
            // this.setTopbarRoutes(defaultRoutes)
            // resolve(rewriteRoutes)
          // })
        })
      }
    }
  })

  // 处理按钮权限
  function getLeafButtonIds(tree, result = []) {
    tree.forEach(node => {
      // 检测是否为末层节点（无 children）
      if (!node.children || node.children.length === 0) {
        // 存在 buttons 时收集 ID
        if (node.buttons?.length) {
          node.buttons.forEach(btn => result.push(btn.id));
        }
      } else {
        // 递归处理子节点
        getLeafButtonIds(node.children, result);
      }
    });
    return result;
  }
// 收集所有菜单ID
  function getAllIds(data) {
    const result = [];
  
    function collectIds(node) {
      if (!node) return; // 处理空值或undefined
      if (Array.isArray(node)) {
        // 处理数组类型的节点（如多根节点）
        node.forEach(child => collectIds(child));
      } else if (typeof node === 'object') {
        // 确保节点有id属性，并将其加入结果
        if (node.id !== undefined) {
          result.push(node.id);
        }
        // 递归处理子节点（确保children是数组）
        if (Array.isArray(node.children)) {
          node.children.forEach(child => collectIds(child));
        }
      }
    }
  
    collectIds(data); // 开始递归
    return result;
  }
  // 处理菜单显示隐藏

  function setTreeHidden(nodes, idSet) {
    // 处理数组类型的节点（如根节点为数组）
    if (Array.isArray(nodes)) {
      return nodes.map(node => processNode(node, idSet));
    }
    // 处理单个节点对象
    return processNode(nodes, idSet);
  }
  function processNode(node, idSet, parentHidden = false) {
    const newNode = { ...node };
    
    // 如果父节点已隐藏，则当前节点强制隐藏
    const currentHidden = parentHidden ? true : !idSet.has(node.id);
    newNode.hidden = currentHidden;
  
    if (newNode.children && newNode.children.length > 0) {
      newNode.children = newNode.children.map(child => 
        processNode(child, idSet, currentHidden) // 传递父节点的隐藏状态
      );
    }
  
    return newNode;
  }

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap, lastRouter = false, type = false) {
  return asyncRouterMap.filter(route => {
    if (type && route.children) {
      route.children = filterChildren(route.children)
    }
    // if (route.component) {
    //   // Layout ParentView 组件特殊处理
    //   if (route.component === 'Layout') {
    //     route.component = Layout
    //   } else if (route.component === 'ParentView') {
    //     route.component = ParentView
    //   } else if (route.component === 'InnerLink') {
    //     route.component = InnerLink
    //   } else {
    //     route.component = loadView(route.component)
    //   }
    // }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children, route, type)
    } else {
      delete route['children']
      delete route['redirect']
    }
    return true
  })
}

function filterChildren(childrenMap, lastRouter = false) {
  var children = []
  childrenMap.forEach(el => {
    el.path = lastRouter ? lastRouter.path + '/' + el.path : el.path
    if (el.children && el.children.length && el.component === 'ParentView') {
      children = children.concat(filterChildren(el.children, el))
    } else {
      children.push(el)
    }
  })
  return children
}

// 动态路由遍历，验证是否具备权限
export function filterDynamicRoutes(routes) {
  const res = []
  routes.forEach(route => {
    if (route.permissions) {
      if (auth.hasPermiOr(route.permissions)) {
        res.push(route)
      }
    } else if (route.roles) {
      if (auth.hasRoleOr(route.roles)) {
        res.push(route)
      }
    }
  })
  return res
}

export const loadView = (view) => {
  console.log(123123123123)
  let res;
  for (const path in modules) {
    const dir = path.split('views/')[1].split('.vue')[0];
    if (dir === view) {
      res = () => modules[path]();
    }
  }
  return res
}

export default usePermissionStore
